package sm.upgrade;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;

import sm.upgrade.api.UpgradePhase;
import sm.util.SMMap;
import sm.util.Util;

public class LanguageKMIdUpgrade implements UpgradePhase {

	private String[] arraySMLangCodes = new String[] { "ar", "be", "bg", "br",
			"ca", "cs", "cy", "da", "de", "el", "en", "es", "et", "fi", "fr",
			"hr", "hu", "is", "it", "iw", "ja", "ko", "lt", "lv", "mk", "mt",
			"nb", "nl", "no", "pl", "pt", "ro", "ru", "sh", "sk", "sl", "sq",
			"sr", "sv", "tr", "uk", "z2", "z3", "zh-Hans", "zh-Hant" };
	private String[] arrayKMLangCodes = new String[] { "ar", null, "bg", "br",
			null, "cs", "cy", "da", "de", "el", "en", "es", "et", "fi", "fr",
			null, "hu", "is", "it", null, "ja", "ko", "lt", "lv", null, "mt",
			"nb", null, null, "pl", "pt", "ro", "ru", null, "sk", "sl", null,
			null, "sv", "tr", null, "th", null, "zh", "zt" };

	private static Logger logger = LoggerFactory.getLogger(UpgradePhase.class);

	private HibernateTemplate template;

	public void setTemplate(HibernateTemplate template) {
		this.template = template;
	}

	@Override
	public void upgrade() {
		logger.info("Updating km.id in language records...");

		List<Object> languages = template.find("from language");
		if (languages != null) {
			for (int i = 0; i < arraySMLangCodes.length; i++) {
				SMMap languageMap = (SMMap) languages.get(i);
				if (Util.equals(arraySMLangCodes[i],
						languageMap.get("unique_id"))
						&& !Util.equals(arrayKMLangCodes[i],
								languageMap.get("km_id"))) {
					languageMap.put("km_id", arrayKMLangCodes[i]);
					template.update("language", languageMap);
				}
			}
		}

		logger.info("  Finished updating km.id in language records.");
	}

}
